package com.ukefu.webim.util.weixin.config;

import com.ukefu.core.UKDataContext;
import com.ukefu.util.UKTools;
import com.ukefu.webim.service.cache.CacheHelper;
import com.ukefu.webim.service.repository.InstructionRepository;
import com.ukefu.webim.service.repository.SNSAccountRepository;
import com.ukefu.webim.util.weixin.handler.MsgHandler;
import com.ukefu.webim.util.weixin.handler.SubscribeHandler;
import com.ukefu.webim.util.weixin.handler.UnsubscribeHandler;
import com.ukefu.webim.web.model.Instruction;
import com.ukefu.webim.web.model.SNSAccount;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.open.api.WxOpenConfigStorage;
import me.chanjar.weixin.open.api.impl.WxOpenInMemoryConfigStorage;
import me.chanjar.weixin.open.api.impl.WxOpenMessageRouter;
import me.chanjar.weixin.open.api.impl.WxOpenServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.NoSuchAlgorithmException;
import java.util.List;

public class WechatOpenConfiguration extends WxOpenServiceImpl {

	private Logger logger = LoggerFactory.getLogger(getClass());

	private WxOpenMessageRouter wxOpenMessageRouter;

	private static WechatOpenConfiguration configuration = new WechatOpenConfiguration() ;

	public static WechatOpenConfiguration getInstance(){
		return configuration ;
	}

	public void init(SNSAccountRepository snsAccountRes) {
		WxOpenConfigStorage configStorage = new WxOpenInMemoryConfigStorage();
		//NOTE 第三方平台配置 使用系统租户
		List<SNSAccount> snsAccountList = snsAccountRes.findBySnstypeAndOrgi(UKDataContext.ChannelTypeEnum.WEIXINTP.toString() , UKDataContext.SYSTEM_ORGI) ;
		if(snsAccountList != null &&snsAccountList.size() > 0){
			SNSAccount snsAccount = snsAccountList.get(0);
			configStorage.setComponentAppId(snsAccount.getAppkey());

			try {
				if(StringUtils.isNotBlank(snsAccount.getSecret())){
					configStorage.setComponentAppSecret(UKTools.decryption(snsAccount.getSecret()));
				}
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			}
			configStorage.setComponentToken(snsAccount.getToken());
			configStorage.setComponentAesKey(snsAccount.getAeskey());
		}

		setWxOpenConfigStorage(configStorage);
		wxOpenMessageRouter = new WxOpenMessageRouter(this);
		/*WxMpMessageHandler handler = new WxMpMessageHandler() {
			@Override
			public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService, WxSessionManager sessionManager) throws WxErrorException {
				logger.info("\n接收到 {} 公众号请求消息，内容：{}", wxMpService.getWxMpConfigStorage().getAppId(), sessionManager);
				return null;
			}
		};*/
		//wxOpenMessageRouter.rule().handler(handler).next();

		wxOpenMessageRouter.rule().async(false).msgType(WxConsts.XmlMsgType.EVENT).event(WxConsts.EventType.SUBSCRIBE).handler(UKDataContext.getContext().getBean(SubscribeHandler.class)).end() ;
		wxOpenMessageRouter.rule().msgType(WxConsts.XmlMsgType.EVENT).event(WxConsts.EventType.UNSUBSCRIBE).handler(UKDataContext.getContext().getBean(UnsubscribeHandler.class)).end() ;
		wxOpenMessageRouter.rule().async(false).handler(UKDataContext.getContext().getBean(MsgHandler.class)).end() ;



		//判断为二维码授权
		/*if(snsAccount != null && StringUtils.isBlank(snsAccount.getSecret())){
			this.getWxOpenConfigStorage().setAuthorizerRefreshToken(snsAccount.getAppkey(),snsAccount.getRefreshtoken());
		}*/
	}

	public void updateWxOpenConfig(SNSAccount snsAccount) {
		WxOpenConfigStorage configStorage = this.getWxOpenConfigStorage();
		configStorage.setComponentAppId(snsAccount.getAppkey());

		try {
			if(StringUtils.isNotBlank(snsAccount.getSecret())){
				configStorage.setComponentAppSecret(UKTools.decryption(snsAccount.getSecret()));
			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		configStorage.setComponentToken(snsAccount.getToken());
		configStorage.setComponentAesKey(snsAccount.getAeskey());
		setWxOpenConfigStorage(configStorage);
	}

	public WxOpenMessageRouter getWxOpenMessageRouter(){
		return wxOpenMessageRouter;
	}

	public void initSNSAccount(SNSAccountRepository snsAccountRes , InstructionRepository insRes){
		this.init(snsAccountRes);
		List<SNSAccount> snsAccountList = snsAccountRes.findBySnstype(UKDataContext.ChannelTypeEnum.WEIXIN.toString()) ;
		for(SNSAccount snsAccount : snsAccountList){
			//判断为二维码授权
			if(StringUtils.isBlank(snsAccount.getSecret())){
				this.getWxOpenConfigStorage().setAuthorizerRefreshToken(snsAccount.getAppkey(),snsAccount.getRefreshtoken());
				/**
				 * 初始化 IMR指令
				 */
				List<Instruction> imrList = insRes.findBySnsidAndOrgi(snsAccount.getSnsid() , snsAccount.getOrgi()) ;
				for(Instruction ins : imrList){
					CacheHelper.getIMRCacheBean().put(ins.getTopic(), ins, ins.getOrgi());
				}
			}
		}
	}

}
